package org.lanicc;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import org.junit.Test;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

/**
 * SimpleHeapOOM
 *
 * @author <p><a href="mailto:1728209643@qq.com">三哥哥</a>
 * @date 2020/1/13 4:00 PM
 */
public class SimpleHeapOOM {


    @Test
    public void testPermOOM() {
        List list = new ArrayList();
        while (true) {
            Enhancer e = new Enhancer();
            //要生成OOMObject类的子类
            e.setSuperclass(O.class);
            e.setUseCache(false);
            //设置callback，对原有对象的调用全部转为调用MethodInterceptor的intercept方法
            e.setCallback((MethodInterceptor) (obj, method, args, proxy) -> {
                System.out.println("Before invoke ");
                Object result = proxy.invokeSuper(obj, args);
                System.out.println("After invoke");
                return result;
            });
            O ee = (O) e.create();
            ee.y();
            list.add(e);
            list.add(ee);
        }
    }

    static class O {
        public void y() {
            System.out.println("o.y()");
        }
    }

    @Test
    public void test2() {
        while (true) {
            ByteBuffer.allocateDirect(1024 * 1024);
        }
    }

    @Test
    public void test1() {
        ArrayList<byte[]> list = new ArrayList<>();
        while (true) {
            list.add(new byte[1024 * 1024]);
        }
    }
}
